#include "utils.h"

/*
 *@brief:
 */
int isAvaliableIpAddress(char * ipAddr){
	int ip[4] = {0};
	int i = 0;
	int elemLen = 0;
	sscanf(ipAddr, "%d.%d.%d.%d", ip, ip+1, ip+2 , ip+3);
	for( i = 0; i < 4; i++){
		if(ip[i] > 0 && ip[i] < 255 ){
			elemLen ++;
		}
	}
	if (elemLen == 4){
		return RET_OK;
	}else{
		return RET_ERROR;
	}
}

/*
 *@brief:
 */
void setfdNoBlock(int fd){
	int iRet = RET_ERROR;
	int flag = 0;
	flag = fcntl(fd, F_GETFL, 0);
	flag |= O_NONBLOCK;
	iRet = fcntl(fd, F_SETFL, flag);
	if(iRet == RET_OK){	
		return;
	}
	fprintf(stderr, "[error]set socket:%d noblock failed!\n", fd);
	return;
}

/*
 *@brief:
 */
int isBigThanZero(int x, int y){
	if ( x >=0 && x < y){
		return RET_OK;
	}else{
		return RET_ERROR;
	}
}

/*
 *@brief:
 */
int setMaxFdSize(int maxconn){
	struct rlimit limit_new;
	int iRet = RET_ERROR;
	limit_new.rlim_cur = limit_new.rlim_max = maxconn;
	iRet = setrlimit(RLIMIT_NOFILE, &limit_new);
	if (iRet == RET_ERROR){
		fprintf(stderr, "[error]%s in file:[%s] func:[%s] line:[%d]\n", strerror(errno),__FILE__, __func__, __LINE__);
		return iRet;
	}
	return RET_OK;
}


/*
 *@
 */
int checkIsNotRootUser(){
	struct passwd *pwd;
	pwd = getpwuid(getuid());
	const char user[] = "root";
	int iRet = RET_ERROR;
	iRet = strncmp(pwd->pw_name, user, strlen(user));
	if(iRet == RET_OK){
		return RET_OK;
	}else{
		fprintf(stderr, "[error]please run this server with root permission!\n");
		return RET_ERROR;
	}
}


/*
 *
 */

int strCaseCmp(const struct dynString *string, const char *command){
	int iRet = RET_ERROR;
	size_t len =  string->len;
	size_t cmdLen = strlen(command);
	iRet = strncasecmp(string->str, command, (len < cmdLen) ? len : cmdLen);
	if(iRet == RET_OK){
		return  len - cmdLen;
	}
	return iRet;
}

/*
 *@brief:
 */
char * httpSkip(char *start, char *end, const char *delims, struct dynString *value){
	value->str =  start;

	while(start < end && strchr(delims, *(unsigned char *)start) == NULL)
		start++;
	value->len = start - value->str;
	while(start < end && strchr(delims, *(unsigned char *)start)!=NULL)
		start++;
	return start;
}


/*
 *@brief:计算每行的字节数;
 *@para:char *buf:
 *		int bufsize:
 *
 */
int getLineLen(char *buf, int bufsize){
	int len = 0;
	while(len < bufsize && buf[len]!='\n') len++;
	return  len == bufsize ? bufsize : len+1;
}


